import {observable, action} from 'mobx'
import { WeaForm,WeaTableNew } from 'comsMobx'
import * as API_LIST from '../apis/fnaInvoiceIdentify'
import * as FnaMessage from '../public/FnaMessage'
import {ConstantStatus} from '../public/FnaConstant'
const {TableStore} = WeaTableNew


/**
 * 发票识别 Store
 */
export class FnaInvoiceIdentifyStore{
    @observable invoiceCloudInfo = {};
    @observable errorInfo = '';
    InvoiceCloudUrlArr = [
		'/corpInvoice/#/component', //设置--开票信息  
    ]	
    @observable securityOriginList = []; 

    @observable loading = false;
    setLoding = (value) => {
        this.loading = value;
    }

    /** 路由 **/
    router = {};
    setRouter = (value) => {
        this.router = value;
    }

    @observable dataKey = "";
    @observable tableStore = new TableStore();

    /****************** 识别 *******************/
    //将识别成功的 发票存起来
    recognitionInvocieIds = [];

    @observable recognitionForm = new WeaForm();
    @observable recognitionCondition = [];
    //文件上传后的ids值
    @observable excelFileNo = [];

    @observable guid = '';

    //保存上传后的ids
    setExcelFileNo = (value) => {
        this.excelFileNo = value;
    }
    /*****************************/
    
    @observable hasRight;//权限的标记 4无权限，跳转

    //识别弹出框显隐
    @observable recognitionVisible = false;

    //识别弹出框显隐
    setRecognitionVisible = (value) => {
        this.recognitionVisible = value;
    }

    uploadEndMsg = [];

    @observable invoiceInfo = {};
    @observable fieldId = '';
    @observable currentBtn = 0;
    @action 
    setCurrentBtn = (value) =>{
        this.currentBtn = value;
    }

    //获取token
	getToken = (value={},callBack) =>{
		API_LIST.getInvoiceCloudToken(value).then( res =>{
			let {invoiceCloud = false,errorInfo,status} = res;
			
			if(status !== '-1'){
				if(invoiceCloud){//发票云
					if(errorInfo){ //无权限
						this.hasRight = 4;
						this.errorInfo = errorInfo;
					}else{
						this.invoiceCloudInfo = {
							token: res.token,
							invoiceCloud: invoiceCloud,
							jsUrl:res.jsUrl,
							baseUrl:res.baseUrl,
                        }

                        this.securityOriginList.push(res.jsUrl);
                        if(res.jsUrl != res.baseUrl){
                            this.securityOriginList.push(res.baseUrl);
                        }
                         
						this.hasRight = 2;
					}
				}else{	//ecology
					this.invoiceCloudInfo = {
						invoiceCloud: invoiceCloud
					}
					this.hasRight = 1;
				}
			}else{
				this.hasRight = 4;
				this.errorInfo = errorInfo;
			}
				
		}) 
			
    }
    
    //搜索
    doSerach = (value = {},flag = false) => {
        this.loading = true;
        API_LIST.getList(value).then( data => {
            let {status,invoiceStatistics=[]} = data;
            if(status == '1'){
                this.hasRight = 1;
                if(flag){//回到第一页
                    this.tableStore.getDatas(data.datas,1);
                }else{
                    this.tableStore.getDatas(data.datas);
                }
                this.dataKey = data.datas;
            } else if(status == '4'){//没有权限
                this.hasRight = 4;
            }    
            this.loading = false;
        });
    }    

    //识别
    doTrainRecognition = (value = {},excelFileNo,callBack) => {
        API_LIST.doRecognition(value).then( data => {
            let {status,uploadMsg,ids} = data;
            if(status == ConstantStatus.FNA_RESULT_SUCCESS || status == ConstantStatus.FNA_RESULT_FAILED){
                if(status == ConstantStatus.FNA_RESULT_SUCCESS){
                    ids && this.recognitionInvocieIds.push();
                    if(!!uploadMsg){
                        this.uploadEndMsg.push(uploadMsg);
                    }
                } else if(status == ConstantStatus.FNA_RESULT_FAILED){
                    uploadMsg && FnaMessage.fnaWarningTip(uploadMsg);
                }
                
                if(excelFileNo.length == 0){
                    let tip = '';
                    if(this.uploadEndMsg.length > 0){
                        this.uploadEndMsg.map((item,index)=>{
                            tip += '<div>'+(index+1)+':'+item+'</div>'
                        });
                        
                    }
                    tip && FnaMessage.fnaWarning(tip);

                    this.uploadEndMsg = [];
                    this.loading = false;
                    this.recognitionVisible = false;
                    callBack && callBack(this.recognitionInvocieIds);
                    return;
                }

                let fileid = excelFileNo.shift();
                let formData = {
                    fptpId:fileid,
                    op:'recognition'
                };

                this.doTrainRecognition(formData,excelFileNo,callBack);

               
            }
        });
    }

    //发起报销单
    addDetail = (value,callBack)=>{
        this.loding = true;
        API_LIST.addDetail(value).then(res =>{
            const {status,msgBuffer} = res;
            if(status == 1){
                if(msgBuffer){
                    FnaMessage.fnaWarningTip(msgBuffer);
                }
                const {fieldindex,fieldIdDate,fieldIdSubject,fieldIdAmount,fieldIdInvoice,fieldIdDesc,idStr,specialobj} = res;
                this.invoiceInfo = {
                    fieldindex: fieldindex,
                    fieldIdDate: fieldIdDate,
                    fieldIdSubject: fieldIdSubject,
                    fieldIdAmount: fieldIdAmount,
                    fieldIdInvoice:fieldIdInvoice,
                    fieldIdDesc: fieldIdDesc,
                    idStr: idStr,
                    specialobj:specialobj
                }
                
                callBack && callBack({invoiceInfo:this.invoiceInfo,desc:res.desc});
            }else{
                FnaMessage.fnaWarning(res.errorInfo)
            }
            this.loding = false;
        })
    } 
    
    //获取fieldId 
    getFieldId = (value={},callBack) =>{
        this.loding = true;
        API_LIST.getFieldId(value).then(res =>{
            const {status,fieldIdInvoice} = res;
            if(status == 1){
                if(fieldIdInvoice){
                    this.fieldId = fieldIdInvoice
                }

                callBack && callBack({fieldId:fieldIdInvoice}) ;
            }else{
                weaAlert('',res.errorInfo,[{text: getLabel(33703, '确认')}]);
            }
            this.loding = false;
        })
    }  
    
    getFidOrEcid = (value={},callBack) =>{
        this.loding = true;
        API_LIST.getFidOrEcid(value).then(res =>{
            const {status,targetIds} = res;
            if(status == 1){
                let targetIdsArr = targetIds.split(',');
                callBack && callBack({targetIds:targetIdsArr});
            }else{
                // weaAlert(res.errorInfo,'',[{text: getLabel(33703, '确认')}]);
            }
            this.loding = false;
        })
    }

    @action
    setSelectedRowKeys = (value=[]) =>{
        this.tableStore.setSelectedRowKeys(value);
    }

    //统一调用 发票云页面
    getInvoiceCloudUrl = (type,arg) => {
        if(!this.invoiceCloudInfo.token) return;

        let userLanguage = window.e9_locale.userLanguage || '7';
        let url = `${this.invoiceCloudInfo.jsUrl}${this.InvoiceCloudUrlArr[type]}?token=${this.invoiceCloudInfo.token}&src=EC&dev=0&baseUrl=${this.invoiceCloudInfo.jsUrl}&lang=${userLanguage}`;

        if(arg){
            Object.keys(arg).forEach( (ele)=>{
                url += `&${ele}=${arg[ele]}`;            
            })
        }
        console.log('url',url)
        return url
        
    }

    @action
    clearData = () =>{
        this.loading = false;
    }
}